import os
import pandas
import json
import numpy


class OperationData(object):
	def __init__(self, file: str):
		"""
		读取测试数据文件
		:param file: 测试数据文件
		"""
		# 获取当前路径
		base_path = os.path.dirname(os.path.dirname(__file__))
		# 拿到Data的路径
		data_path = os.path.join(base_path, "Data")
		# 定位到文件
		file_path = os.path.join(data_path, file)
		# 判断文件格式
		if file_path.endswith("xls"):
			self.table = pandas.read_excel(file_path, keep_default_na=False)  # 读取xls文件
		elif file_path.endswith("csv"):
			self.table = pandas.read_csv(file_path, keep_default_na=False)  # 读取csv文件
		else:
			self.table = None
			print("请选择指定格式的文件(csv或xls)")

	def get_data_to_list(self):
		"""
		将文件内容读取成列表嵌套列表格式
		:return:
		"""
		if self.table is not None:
			return self.table.values.tolist()
		else:
			return None

	def get_data_to_dict(self):
		"""
		将文件内容读取成为列表嵌套字典格式
		:return:
		"""
		if self.table is not None:
			return [self.table.loc[i].to_dict() for i in self.table.index.values]
		else:
			return None

	def new_dict(self):
		"""新列表嵌套字典"""
		dict_str = json.dumps(self.get_data_to_dict(), cls=NpEncoder)  # 将int64字段,转为int
		return json.loads(dict_str)

	def new_list(self):
		"""新列表嵌套列表"""
		list_str = json.dumps(self.get_data_to_list(), cls=NpEncoder)
		return json.loads(list_str)


# 处理pandas读取CSV/excel中整数数据类型
class NpEncoder(json.JSONEncoder):
	def default(self, obj):
		if isinstance(obj, numpy.integer):  # numpy.integer 是int64
			return int(obj)
		elif isinstance(obj, numpy.floating):
			return float(obj)
		elif isinstance(obj, numpy.ndarray):
			return obj.tolist()
		else:
			return super(NpEncoder, self).default(obj)


if __name__ == '__main__':
	opera = OperationData('login_data.xls')
	print(opera.new_dict())
	print(opera.new_list())
